package com.qfedu.common.core.interceptor;

import com.qfedu.common.core.annotation.NoLogin;
import com.qfedu.common.core.utils.JwtUtils;
import com.qfedu.common.core.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Classname LoginInterceptor
 * @Description TODO
 * @Date 2025-05-22 11:49
 * @Created by 老任与码
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 控制层方法封装为handlerMethod对象
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            Method method = handlerMethod.getMethod();
            // 判断访问的控制层方法是否使用了注解
            boolean ret = method.isAnnotationPresent(NoLogin.class);
            // 如果存在，直接放行
            if (ret) {
                return true;
            }

            // 如果没有注解，判断登录状态
            String token = request.getHeader("Token");
            if (token == null || token.isEmpty()) {
                throw new RuntimeException("请重新登录");
            }
            //token存在，可以正常解析
            try {
                Claims claims = JwtUtils.parseJWT(token);
                // 将解析的用户id存入ThreadLocal
                UserUtils.setUid((Integer) claims.get("uid"));
            } catch (Exception e) {
                throw new RuntimeException("请重新登录");
            }
        }

        return true;
    }
}
